#include "utils/thread_pool.h"
#include <iostream>
#include <iomanip> // 用于std::setw和std::setfill，格式化输出
#include <chrono>
#include <random>
#include <string>

// 简单测试：验证基本功能
void test_simple() {
	std::cout << "=== 简单功能测试 === " << std::endl;

	size_t     n = std::thread::hardware_concurrency(); // 双倍核心数
	ThreadPool pool(n > 0 ? n : 4);
	std::cout << "线程池大小: " << pool.size() << std::endl;

	// 入队普通函数
	pool.enqueue([](const std::string &name) { std::cout << "Hello " << name << std::endl; }, "World");
	pool.enqueue([](int a, int b) { std::cout << a << " + " << b << " = " << a + b << std::endl; }, 2, 3);

	// 入队lambda并获取结果
	auto future = pool.enqueue([]() -> int {
		std::this_thread::sleep_for(std::chrono::milliseconds(100));
		return 42;
	});

	std::cout << "Lambda返回值: " << future.get() << std::endl;
	pool.waitAll();
}

// 并发计数测试：验证线程安全和计数准确性
void test_concurrent_counting() {
	std::cout << "=== 并发计数测试 === " << std::endl;
	size_t     n = std::thread::hardware_concurrency();
	ThreadPool pool(n > 0 ? n : 4); // 自动适配硬件并发数

	auto      counter    = std::make_shared<size_t>(0);
	auto      mtx        = std::make_shared<std::mutex>(); // 保护计数器的互斥锁
	const int task_count = 50;

	for (int i = 0; i < task_count; ++i) {
		pool.enqueue([counter, mtx, &pool, i]() {
			std::this_thread::sleep_for(std::chrono::microseconds(1000 + rand() % 1000));
			std::lock_guard<std::mutex> lock(*mtx);
			++(*counter);
			std::cout << "线程ID: " << std::this_thread::get_id() << " 任务: " << std::setw(2) << std::setfill('0') << i << " 活动任务: " << pool.activeCount()
			          << " 等待任务: " << pool.pendingCount() << " 计数: " << *counter << std::endl;
		});
	}

	pool.waitAll();
	std::cout << "最终计数: " << *counter << " (预期: " << task_count << ")" << std::endl;
}

// 测试返回值：验证future的正确性
void test_future_results() {
	std::cout << "=== 测试返回值 === " << std::endl;
	ThreadPool                    pool(2);
	std::vector<std::future<int>> futures;
	for (int i = 0; i < 5; ++i) {
		futures.emplace_back(pool.enqueue([i]() -> int {
			std::this_thread::sleep_for(std::chrono::milliseconds(100 * i));
			return i * i;
		}));
	}

	for (auto &fut: futures) {
		std::cout << "计算结果: " << fut.get() << std::endl;
	}
}

// 测试队列限制：验证队列满时的阻塞行为
void test_queue_limit() {
	std::cout << "=== 测试任务队列限制 === " << std::endl;
	ThreadPool pool(1, 5); // 1个线程，队列最大5个任务
	auto       start = std::chrono::high_resolution_clock::now();

	// 添加10个任务（队列满时会阻塞）
	for (int i = 0; i < 10; ++i) {
		pool.enqueue([i]() {
			std::this_thread::sleep_for(std::chrono::milliseconds(100));
			std::cout << "完成任务 " << i << std::endl;
		});
		std::cout << "添加任务 " << i << "，当前等待任务数: " << pool.pendingCount() << std::endl;
	}

	pool.waitAll();
	auto                          end     = std::chrono::high_resolution_clock::now();
	std::chrono::duration<double> elapsed = end - start;
	std::cout << "总耗时: " << elapsed.count() << "秒 (预期约1秒)" << std::endl;
}


// 编译： 		g++ -std=c++11 -pthread thread_pool_example.cpp -o thread_pool_example.exe
// Cmake运行：  make testx name=thread_pool_test
int main() {
	srand(time(nullptr)); // 初始化随机数种子，用于随机休眠时间

	test_simple();
	test_concurrent_counting();
	test_future_results();
	test_queue_limit();
	return 0;
}
